package com.mvp.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.FloatRange;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.jakewharton.rxbinding3.view.RxView;
import com.mvp.R;
import com.mvp.helper.WCallBack;
import com.mvp.utils.DisplayUtils;

import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;

/**
 * Created by zhangyuncai on 2019/5/29.
 */
public abstract class BaseDialogFragment extends DialogFragment implements View.OnClickListener, LoadMvpView {
    protected Activity mActivity;
    protected Context mContext;
    protected View rootView;
    protected Unbinder unbinder;
    protected CompositeDisposable composite;
    protected DialogInterface.OnDismissListener onDismissListener;
    protected WCallBack callBack;

    public <T> void setCallBack(WCallBack<T> callBack) {
        this.callBack = callBack;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        mActivity = (Activity) context;
        this.composite = new CompositeDisposable();
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog == null) {
            return;
        }
        // 设置宽度为屏宽, 靠近屏幕底部。
        Window window = getDialog().getWindow();
        if (window == null) {
            return;
        }
        //设置窗体背景色透明
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //设置宽高
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = getWidthStyle();
        layoutParams.height = getHeightStyle();
        //透明度
//        layoutParams.dimAmount = getDimAmount();
        //位置
        layoutParams.gravity = getGravity();
        window.setAttributes(layoutParams);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutId(), container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //去除Dialog默认头部
        Dialog dialog = getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(isCancelableOutside());
        if (dialog.getWindow() != null && getDialogAnimationRes() > 0) {
            dialog.getWindow().setWindowAnimations(getDialogAnimationRes());
        }
        initViewBefore(savedInstanceState);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initEvent();
        initData();
    }

    protected void initViewBefore(@Nullable Bundle savedInstanceState) {

    }


    public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (onDismissListener != null) {
            onDismissListener.onDismiss(dialog);
        }
    }

    /**
     * 防止双击
     *
     * @param v
     */
    public void onFilterDoubleClick(View v) {
        Disposable subscribe = RxView.clicks(v)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    onClick(v);
                });
        composite.add(subscribe);
    }

    /**
     * 防止双击
     *
     * @param v
     */
    public void onFilterDoubleClick(View v, View.OnClickListener clickListener) {
        Disposable subscribe = RxView.clicks(v)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    clickListener.onClick(v);
                });
        composite.add(subscribe);
    }

    @Override
    public void onClick(View v) {

    }

    protected abstract @LayoutRes
    int getLayoutId();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void initEvent();


    protected boolean isCancelableOutside() {
        return true;
    }

    //获取弹窗显示动画,子类实现
    protected int getDialogAnimationRes() {
        return 0;
    }

    //默认透明度为0.2
    public float getDimAmount() {
        return 0.2f;
    }

    /**
     * 获取 dialog 显示在界面的位置样式
     *
     * @return 位置样式
     */
    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    /**
     * 获取 dialog 显示在界面的动画样式
     *
     * @return 位置样式
     */
    protected int getAnimations() {
        return R.style.DataSheetAnimation;
    }

    /**
     * 子类复写 去实现 dialog 宽度的选择
     *
     * @return dialog宽度
     */
    protected int getWidthStyle() {
        return WindowManager.LayoutParams.MATCH_PARENT;
    }

    /**
     * 子类复写 去实现 dialog 高度的选择
     *
     * @return dialog高度
     */
    protected int getHeightStyle() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }

    /**
     * 获取屏幕高度
     *
     * @return
     */
    protected int getScreenHeight() {
        int dialogHeight = getContextRect(mActivity);
        if (dialogHeight == 0) {
            return ViewGroup.LayoutParams.MATCH_PARENT;
        } else {
            return dialogHeight;
        }
    }

    /**
     * 解决DialogFragment全屏时状态栏变黑
     * 获取内容区域
     *
     * @param activity
     * @return
     */
    protected int getContextRect(Activity activity) {
        //应用区域
        Rect outRect1 = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
        return outRect1.height();
    }

    //获取屏幕宽度的百分比
    protected int getScreenWidth(@FloatRange(from = 0.1f, to = 1f) float percent) {
        return (int) (DisplayUtils.getScreenWidthAndHight(getContext())[0] * percent);
    }

    public void show(FragmentManager manager, String tag) {
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commit();
            super.show(manager, tag);
        } catch (Exception e) {
            //同一实例使用不同的tag会异常,这里捕获一下
            e.printStackTrace();
        }
    }

    @Override
    public void showLoadingBar(Object showTag) {
        if (getActivity() != null && getActivity() instanceof LoadMvpView) {
            ((LoadMvpView) getActivity()).showLoadingBar(showTag);
        }
    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        if (getActivity() != null && getActivity() instanceof LoadMvpView) {
            ((LoadMvpView) getActivity()).dismissLoadingBar(dississTag);
        }
    }

    @Override
    public void showLoadingFailureError(Throwable throwable) {
        if (getActivity() != null && getActivity() instanceof LoadMvpView) {
            ((LoadMvpView) getActivity()).showLoadingFailureError(throwable);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null)
            unbinder.unbind();

        if (composite != null && !composite.isDisposed()) {
            composite.dispose();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Timber.d(String.format("--->>>>>>>>---%s:setUserVisibleHint,页面显示隐藏======>%s", getClass().getSimpleName(), isVisibleToUser));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Timber.d(String.format("--->>>>>>>>---%s:onHiddenChanged,页面显示隐藏======>%s", getClass().getSimpleName(), hidden));
    }
}
